﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Hotel.Vendor.InterfacePlatformManage.Entity.HTicketEntity;
using Hotel.Vendor.InterfacePlatformManage.Business.HTicketBusiness;
using Hotel.Vendor.InterfacePlatformManage.OfflineSite.Page;
using HTicket.Entity;
using HTicket.Constant;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace HTicket
{
    /// <summary>
    /// Summary description for AjaxHandler
    /// </summary>
    public class AjaxHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string argsType = context.Request["type"];
            Action(argsType, context);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void Action(string type, HttpContext context)
        {
            string data = string.Empty;
            switch (type)
            {
                case "addTask":
                    data = context.Request["addData"];
                    InsertTask(data, context);
                    break;
                case "replayTask":
                    data = context.Request["replayData"];
                    ReplayTask(data, context);
                    break;
                case "getCookies":
                    GetCookies(context);
                    break;
                case "delCookies":
                    DelCookies();
                    break;
                case "chart":
                    string startTime = context.Request["startTime"];
                    string endTime = context.Request["endTime"];
                    GetChartXML(context, startTime, endTime);
                    break;
            }
        }

        /// <summary>
        /// 获取饼图/柱状图XML
        /// </summary>
        public void GetChartXML(HttpContext context, string startTime, string endTime)
        {
            UserViewModel userInfo = JsonConvert.DeserializeObject<UserViewModel>(context.Request.Cookies["User"].Value);

            ChartEntity chart = new ChartEntity();
            chart.Caption = HTicketConstant.ChartTitle;
            chart.NumberPrefix = HTicketConstant.ChartPrefix;
            chart.Set = new List<ChartSet>();

            var chartList = HotelInterfaceTaskListProcessBusiness.GetChartList(userInfo.GroupInfo.GroupID, startTime, endTime);
            chartList.ForEach(item =>
            {
                ChartSet set = new ChartSet();
                set.Label = item.Label;
                set.Value = item.Value;
                chart.Set.Add(set);
            });

            context.Response.Write(this.Serializer(typeof(ChartEntity), chart));
        }

        /// <summary>
        /// 获取Json Cookies
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public void GetCookies(HttpContext context)
        {
            string cookies = context.Request.Cookies["User"].Value;
            context.Response.Write(cookies);
        }

        /// <summary>
        /// 删除Cookies
        /// </summary>
        public void DelCookies()
        {
            HTicketPage.DelCookie(HTicketConstant.UserCookiesName);
        }


        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public void InsertTask(string data, HttpContext context)
        {
            string text = string.Empty;
            UserViewModel userInfo = JsonConvert.DeserializeObject<UserViewModel>(context.Request.Cookies["User"].Value);

            try
            {

                //新增Task，插入主表
                var processViewModel = JsonConvert.DeserializeObject<HotelInterface_TaskListProcess>(data);
                processViewModel.AddTime = DateTime.Now.ToString();
                processViewModel.EID = userInfo.EID;
                processViewModel.HandleMan = userInfo.Name;
                processViewModel.State = "0";     //添加任务时候状态为0(New)
                string taskID = HotelInterfaceTaskListProcessBusiness.InsertTaskListProcess(processViewModel);


                //新增Task，插入从表
                HotelInterfaceTaskListProcessContentEntity contentEntity = new HotelInterfaceTaskListProcessContentEntity();
                contentEntity.Content = processViewModel.Content;
                contentEntity.Eid = processViewModel.EID;
                contentEntity.Flag = "Q";
                contentEntity.TaskID = int.Parse(taskID);
                contentEntity.DataChange_LastTime = processViewModel.AddTime;
                HotelInterfaceTaskListProcessBusiness.InsertTaskListProcessContentLog(contentEntity);

                EmailSendViewModel emailSendViewModel = new EmailSendViewModel
                {
                    EID = processViewModel.EID,
                    Importance = processViewModel.Importance,
                    Subject = processViewModel.Subject,
                    ProjectId = processViewModel.ProjectId,
                    Content = processViewModel.Content,
                    ActionType = processViewModel.ActionType,
                    TaskID = processViewModel.TaskID.ToString(),
                    HandleMan = processViewModel.HandleMan
                };

                //发送Email
                HTicketPage.SendEmail(emailSendViewModel, "", taskID);

                text = "true";
            }
            catch (Exception)
            {
                text = "false";
            }

            context.Response.Write(text);
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public void ReplayTask(string data, HttpContext context)
        {
            string text = string.Empty;

            try
            {

                UserViewModel userInfo = JsonConvert.DeserializeObject<UserViewModel>(context.Request.Cookies["User"].Value);
                var processViewModel = JsonConvert.DeserializeObject<HotelInterfaceTaskListProcessContentEntity>(data);

                //回复过程(插入HotelInterface_TaskListProcessContentLog)
                HotelInterfaceTaskListProcessContentEntity contentEntity = new HotelInterfaceTaskListProcessContentEntity();
                contentEntity.Content = processViewModel.Content;
                contentEntity.Eid = userInfo.EID;
                contentEntity.Flag = "A";
                contentEntity.TaskID = processViewModel.TaskID;
                contentEntity.DataChange_LastTime = DateTime.Now.ToString();
                HotelInterfaceTaskListProcessBusiness.InsertTaskListProcessContentLog(contentEntity);

                //更新HotelInterface_TaskListProcess表
                HotelInterface_TaskListProcess listProcess = new HotelInterface_TaskListProcess();
                listProcess.TaskID = processViewModel.TaskID;
                listProcess.State = processViewModel.State;
                listProcess.HandleMan = processViewModel.HandleMan;
                listProcess.Importance = processViewModel.Importance;
                HotelInterfaceTaskListProcessBusiness.UpdateHotelInterface_TaskListProcess(listProcess);

                //发送Email
                EmailSendViewModel emailSendViewModel = new EmailSendViewModel
                {
                    EID = contentEntity.Eid,
                    Importance = processViewModel.Importance,
                    Subject = processViewModel.Subject,
                    ProjectId = processViewModel.ProjectID,
                    Content = processViewModel.Content,
                    ActionType = processViewModel.ActionType,
                    TaskID = processViewModel.TaskID.ToString(),
                    HandleMan = processViewModel.HandleMan
                };

                HTicketPage.SendEmail(emailSendViewModel, "", processViewModel.TaskID.ToString());

                text = "true";
            }
            catch (Exception)
            {
                text = "false";
            }

            context.Response.Write(text);
        }

        /// <summary>
        /// 序列化XML
        /// </summary>
        /// <param name="type"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            //创建序列化对象  
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象  
                XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
                xmlns.Add(String.Empty, String.Empty);
                xml.Serialize(Stream, obj, xmlns);

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();
            string tag = "<?xml version=\"1.0\"?>";
            return str.Replace(tag, "").Trim();
            //var a = "<Chart Caption=\"HTickets\" NumberPrefix=\"HTickets-\"><Set Label=\"A\" Value=\"0\" /><Set Label=\"A\" Value=\"1\" /><Set Label=\"A\" Value=\"2\" /><Set Label=\"A\" Value=\"3\" /></Chart>";
            //return a;
        }
    }
}